package com.song.flowable.util;

import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;

public class FileUtil {
    public static String readXmlToString(String filepath){
        try {
            // 创建一个DocumentBuilderFactory
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // 通过DocumentBuilderFactory创建一个DocumentBuilder
            DocumentBuilder builder = factory.newDocumentBuilder();
            // 通过DocumentBuilder读取XML内容到Document对象
            Document document = builder.parse(filepath);

            // 创建TransformerFactory
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            // 通过TransformerFactory创建Transformer
            Transformer transformer = transformerFactory.newTransformer();

            // 将DOM Document内容转换为字符串
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(document), new StreamResult(writer));

            // 输出XML字符串
            String xmlString = writer.toString();
            return xmlString;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
